package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-24
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getToSale() {
        return baseMapper.selectToSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, skuId).select(ProductSku::getMarketPrice, ProductSku::getSalePrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        //封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, id).select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        //封装数据
        HashMap<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    /**
     * 根据skuId查询sku商品信息
     *
     * @param skuId
     * @return
     */
    @Override
    public ProductSku getProductSku(Long skuId) {
        //获取锁
        String lockKey = "product:sku:lock" + skuId;
        String lockValue = UUID.randomUUID().toString();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
        if (flag) {
            try {
                //业务代码
                //先从缓存中获取商品，如果存在则将商品返回，然后将数据存入缓存
                String dataKey = "product:sku:" + skuId;
                ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                if (productSku != null) {
                    log.warn("命中缓存");
                    return productSku;
                }
                //如果不存在，则从数据库中查询，并保存到缓存中
                log.warn("未命中缓存");
                productSku = baseMapper.selectById(skuId);

                //如果值为null，则存储一个new初始化对象
                long ttl = productSku == null ? 60 : 10 * 60;
                if (productSku == null) {
                    productSku = new ProductSku();
                }
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);
                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                String script = """
                        if redis.call('get', KEYS[1]) == ARGV[1] then
                                                return redis.call('del', KEYS[1])
                                            else
                                                return 0
                                            end
                        """;
                Long lock = (Long) redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                        Arrays.asList(lockKey), lockValue);
                System.out.println("释放锁的结果为:" + lock);
            }
        } else {
            //获取锁失败 自旋
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return this.getProductSku(skuId);
        }
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        //根据skuid列表批量查询商品的最新价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId, skuIdList);
        queryWrapper.select(ProductSku::getId, ProductSku::getSalePrice);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(productSkuList)) {
            return productSkuList.stream()
                    .map(productSku -> {
                        SkuPriceVo skuPriceVo = new SkuPriceVo();
                        skuPriceVo.setSalePrice(productSku.getSalePrice());
                        skuPriceVo.setSkuId(productSku.getId());
                        return skuPriceVo;
                    }).collect(Collectors.toList());
        }
        return null;
    }
}
